package org.easy.tool.common;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author Valley
 * 2025/2/17 18:36
 */
public class DeepSeekUtil {

    public static final String API_URL = "https://infer-modelarts-cn-southwest-2.modelarts-infer.com/v1/infers/952e4f88-ef93-4398-ae8d-af37f63f0d8e/v1/chat/completions";
    public static final String API_KEY = "kk7fXAPyTLFHZ7Psl0xQeD-lKowEZey9pKiKt6PeieYM5FT8BxTkDH6lbEWmvwexVU4CXHYECHes-TOE9-VZXA";

    public static String askAI(String question) {
        ObjectMapper mapper = new ObjectMapper();
        StringBuilder completeResult = new StringBuilder();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(API_URL);
            httpPost.setHeader("Authorization", "Bearer " + API_KEY);
            httpPost.setHeader("Content-Type", "application/json");

            // 设置请求体（如果 API 需要）
            LinkedHashMap body = new LinkedHashMap();
            body.put("model", "DeepSeek-R1");
            body.put("max_tokens", 9999);
            LinkedHashMap message = new LinkedHashMap();
            message.put("role", "user");
            message.put("content", question);
            body.put("messages", Collections.singleton(message));
            body.put("stream", true);
            LinkedHashMap streamOption = new LinkedHashMap();
            streamOption.put("include_usage", true);
            body.put("stream_option", streamOption);
            body.put("temperature", 1.0);
            String requestBody = mapper.writeValueAsString(body);
            httpPost.setEntity(new StringEntity(requestBody));
            HttpResponse response = httpClient.execute(httpPost);
            // 读取响应流
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.trim().isEmpty()) continue; // 跳过空行
                    if (line.contains("[DONE]")) break;
                    LinkedHashMap map = mapper.readValue(line, LinkedHashMap.class);
                    List choices = (List) map.get("choices");
                    if (!choices.isEmpty()){
                        LinkedHashMap choice = (LinkedHashMap) choices.get(0);
                        LinkedHashMap delta = (LinkedHashMap) choice.get("delta");
                        Object reason = delta.get("reasoning_content");
                        Object content = delta.get("content");
                        if (reason != null){
                            completeResult.append(reason);
                        }else if (content != null){
                            completeResult.append(content);
                        }
                    }
                }
                System.out.println("完整结果: " + completeResult.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return completeResult.toString();
    }

}
